<template>
	<!-- 生产工单开立 -->
	<div>
		<v-stepper v-model="pdmProjectEL">
			<v-stepper-header>
				<v-stepper-step :complete="pdmProjectEL > 1" step="1">
					加工交期维护
				</v-stepper-step>
				<v-stepper-step step="2">
					零件工艺、交期维护
				</v-stepper-step>
			</v-stepper-header>

			<v-stepper-items>
				<!-- 选择项目信息 -->
				<v-stepper-content step="1">
					<v-row class='minheight pa-4 overflow-x-auto' justify="space-between">
						<v-col cols="6" dense>
							<v-card ref="projectRef" height="600">
								<v-alert dense text color="blue-grey">
									PDM项目查看
								</v-alert>
								<v-card-title>
									<v-row>
										<v-col cols="12" sm="3" md="3">
											<v-text-field label="项目号" v-model="projectCode" placeholder="项目号" dense
												outlined>
											</v-text-field>
										</v-col>
										<!-- sm="6" md="2" -->
										<v-col cols="12" sm="3" md="3">
											<v-text-field label="项目名称" v-model="projectName" placeholder="项目名称" dense
												outlined>
											</v-text-field>
										</v-col>
										<v-col cols="12" sm="3" md="3">
											<v-text-field label="设备名称" v-model="equipmentName" placeholder="设备名称" dense
												outlined>
											</v-text-field>
										</v-col>

										<!-- ml-n16 前面加n是间距 -->
										<!-- class="ml-n16 mx-auto" -->
										<v-col cols="12" sm="6" md="3">
											<v-btn depressed color="primary" @click="projectQuery">查询</v-btn>
											<v-btn class="ml-3" depressed color="primary" @click="refreshProjectQuery">
												刷新</v-btn>
										</v-col>
									</v-row>
								</v-card-title>

								<v-data-table dense class="elevation-1 text-no-wrap" :headers="projectHeaders"
									:items="projectData" :loading="projectLoading" :options.sync="projectOptions"
									:footer-props="vuetifyDefaultPage" :server-items-length="projectTotalCount"
									item-selected="projectItemSelect" item-key="id" show-select single-select
									loading-text="正在加载请稍等......" @input="currentSelectProjects"
									@item-selected="itemProjectSelected">
								</v-data-table>
							</v-card>
						</v-col>
						<v-col cols="6" dense>
							<v-card height="600">
								<v-alert dense text color="blue-grey">
									设备交期维护
								</v-alert>
								<v-card-title>
									<v-btn v-if="currentSelectOneProject!=null" class="ml-2" small tile color="success"
										@click="batchDeliveryDateEvent">
										批量交期维护
									</v-btn>
									<v-divider class="mx-4" inset vertical></v-divider>
									<v-text-field v-if="currentSelectOneProject!=null" v-model="projectDetailSearch"
										append-icon="mdi-magnify" label="搜索" single-line hide-details></v-text-field>
								</v-card-title>

								<v-data-table v-if="currentSelectOneProject!=null" dense
									class="elevation-1 text-no-wrap" :headers='[{"text":"选中项","value":"check"},
									{"text":"操作","value":"actions","align": "center"},
									{"text":"名称","value":"name"},
									{"text":"交期","value":"deliverydate"},
									{"text":"类型","value":"typename"},
									{"text":"数量","value":"qty"}]' :items="currentSelectOneProject.projectDetailList" item-key="id"
									loading-text="正在加载请稍等......" :search="projectDetailSearch"
									:footer-props="vuetifyDefaultPage">

									<template v-slot:item.check="{item }">
										<v-checkbox v-model="item.check" style="height:20px;" class="mb-5"></v-checkbox>
									</template>
									<template v-slot:item.actions="{ item }">
										<div>
											<v-btn class="ml-2" small tile color="success"
												:disabled="item.deliverydate!=null"
												@click="deliveryDateVisable=true,checkCurrentProjectDetail(item)">
												<v-icon small left>
													mdi-wrench
												</v-icon>
												交期维护
											</v-btn>
										</div>
									</template>
								</v-data-table>

							</v-card>
						</v-col>
					</v-row>
					<v-container row class="text-subtitle-1 d-flex justify-center  align-left">
						<br />
						<v-spacer></v-spacer>
						<v-btn class="ml-3" color="primary" @click="pdmProjectEL = 2,loadChildrenOrder()">
							下一步
						</v-btn>
					</v-container>
				</v-stepper-content>
				<!-- 选择母工单信息 -->
				<v-stepper-content step="2">
					<v-card>
						<v-alert dense text color="blue-grey">
							勾选母工单维护零件交期与类型
						</v-alert>
						<v-card-title>
							<v-text-field v-if="masterOrderData!=null" v-model="masterOrderSearch"
								append-icon="mdi-magnify" label="搜索" single-line hide-details></v-text-field>
						</v-card-title>
						<v-data-table dense class="elevation-1 text-no-wrap" :headers="masterHeaders"
							:items="masterOrderData" item-key="id" show-select single-select :search="masterOrderSearch"
							:footer-props="vuetifyDefaultPage" @item-selected="masterOrderCheckEvent">
						</v-data-table>

						<v-tabs left dense>
							<v-tab>零件与工单信息</v-tab>
							<v-tab-item height=180>
								<v-container fluid>
									<v-row class='minheight pa-4 overflow-x-auto' justify="space-between">
										<v-col cols="6" dense>
											<v-alert dense text color="blue-grey">
												项目零件信息
											</v-alert>

											<v-text-field v-if="currentProjectPartList!=null" v-model="partSearch"
												append-icon="mdi-magnify" label="搜索" single-line hide-details>
											</v-text-field>

											<v-data-table dense class="elevation-1 text-no-wrap" :headers="[
												 {'text':'操作','value':'actions',	align: 'center'},
												{'text':'数量','value':'totalcount'},
												{'text':'单位','value':'unit'},
												 {'text':'图号','value':'piccode'},
												 {'text':'名称','value':'name'},
												 {'text':'类型','value':'parttypename'},
										 {'text':'规格型号','value':'specifications'},
										  {'text':'结构','value':'keypathname'},
										 {'text':'交期','value':'deliverydate'},
										 {'text':'工艺属性','value':'typename'},
										  {'text':'加工件编号','value':'code'},
										 ]" :items="currentProjectPartList" item-key="id"
											show-select 
											:search="partSearch"
											:footer-props="vuetifyDefaultPageShowParts"
											@input="selectPartsEvent"
											>
												<template v-slot:item.parttypename="{ item }">
													<a v-if="item.parttype==3"
														style="color: #67C23A;">{{item.parttypename}}</a>
													<a v-else style="color: #C7C7C7;">{{item.parttypename}}</a>
												</template>
												<!-- 零件维护工艺 -->
												<template v-slot:item.actions="{ item }">
													<div>
														<v-btn :disabled="item.deliverydate!=null||item.parttype!=3"
															class="ml-2" small tile color="success"
															@click="partItemClick(item)">
															交期维护
														</v-btn>

													</div>
												</template>
											</v-data-table>
										</v-col>
										<v-divider vertical></v-divider>
										<v-col cols="5" max-width="200">
											<v-alert dense text color="blue-grey">
												子工单信息
											</v-alert>
											<v-text-field v-if="childrenOrderData!=null" v-model="childrenSearch"
												append-icon="mdi-magnify" label="搜索" single-line hide-details>
											</v-text-field>
											<v-data-table dense class="elevation-1 text-no-wrap" :headers="[{'text':'零件名称','value':'name'},
										 {'text':'子工单号','value':'code'},
										 {'text':'图号','value':'piccode'},
										{'text':'材料','value':'material'},
										{'text':'规格型号','value':'specifications'},
											{'text':'单套数量','value':'singlecount'},
												{'text':'总数','value':'totalcount'},
													{'text':'单位','value':'unit'},
														{'text':'表面处理','value':'surface_treatment'},
														{'text':'交期','value':'deliverydate'},
																{'text':'出入库环节','value':'outinstoragelinkname'},
																	{'text':'确认日期','value':'confirmdate'},
																		{'text':'备注','value':'description'},
										 ]" :items="childrenOrderData" item-key="id" :search="childrenSearch" :footer-props="vuetifyDefaultPage">
											</v-data-table>
										</v-col>
									</v-row>



									<v-dialog v-model="partDialogVisable" max-width="750px">
										<v-card>
											<v-card-title>
												<span class="text-h5">工艺及交期维护</span>
											</v-card-title>
											<!-- 对话框内的字段内容 -->
											<v-card-text>
												<v-container>
													<v-row>
														<v-col cols="12">

															<v-select class="mt-6" required
																v-model="selectChildrenOrderType"
																:items="childrenOrderTypes" dense label="选择工艺属性">
															</v-select>
														</v-col>
														<v-col cols="12">
															<v-menu v-model="childrenDeliverydateMenu"
																:close-on-content-click="false" :nudge-right="40"
																transition="scale-transition" offset-y min-width="auto">
																<template v-slot:activator="{ on, attrs }">
																	<v-text-field required
																		v-model="childrenDeliverydate" label="交期"
																		readonly v-bind="attrs" v-on="on">
																	</v-text-field>
																</template>
																<v-date-picker locale="zh-cn"
																	v-model="childrenDeliverydate"
																	@input="childrenDeliverydateMenu = false">
																</v-date-picker>
															</v-menu>
														</v-col>
														<v-col cols="12">
															<v-text-field v-model="selectAssemblyMasterOrder.text"
																disabled></v-text-field>
														</v-col>
													</v-row>
												</v-container>
											</v-card-text>

											<v-card-actions>
												<v-spacer></v-spacer>
												<v-btn color="blue darken-1" text @click="savePart">生成子工单
												</v-btn>
												<v-btn color="blue darken-1" text @click="closePart">取消</v-btn>
												<v-spacer></v-spacer>
											</v-card-actions>
										</v-card>
									</v-dialog>
								</v-container>
							</v-tab-item>
						</v-tabs>

					</v-card>
					<br />
					<v-container row class="text-subtitle-1 d-flex justify-center  align-left">
						<v-spacer></v-spacer>
						<v-btn color="primary" @click="pdmProjectEL = 1,loadChildrenOrder()">
							上一步
						</v-btn>
					</v-container>
				</v-stepper-content>
				<!-- 维护零件生成子工单信息 -->
			</v-stepper-items>
		</v-stepper>

		<v-dialog v-model="deliveryDateVisable" max-width="500px">
			<v-card>
				<!-- 对话框内标题 -->
				<v-card-title>
					<span class="text-h5">交期维护</span>
				</v-card-title>
				<!-- 对话框内的字段内容 -->
				<v-card-text>
					<v-container>
						<v-row>
							<v-col cols="12">
								<v-menu v-model="deliverydateMenu" :close-on-content-click="false" :nudge-right="40"
									transition="scale-transition" offset-y min-width="auto">
									<template v-slot:activator="{ on, attrs }">
										<v-text-field required v-model="deliverydate" label="交期" readonly v-bind="attrs"
											v-on="on">
										</v-text-field>
									</template>
									<v-date-picker locale="zh-cn" v-model="deliverydate"
										@input="deliverydateMenu = false">
									</v-date-picker>
								</v-menu>
							</v-col>
						</v-row>
					</v-container>
				</v-card-text>

				<v-card-actions>
					<v-spacer></v-spacer>
					<v-btn color="blue darken-1" text @click="save">生成母工单</v-btn>
					<v-btn color="blue darken-1" text @click="close">取消</v-btn>
				</v-card-actions>
			</v-card>
		</v-dialog>
		<emailcomment :emailModel="emailCommentModel" :callBack="sendEmailCallBack"></emailcomment>
	</div>
</template>

<script>
	import emailComment from '../components/SendEmail.vue'
	import {
		format,
		parseISO
	} from 'date-fns'
	export default {
		name: 'mes_production_workorder_initial',
		components: {
			emailcomment: emailComment
		},
		data() {
			return {
				emailCommentModel: {
					sendEmailDialogVisable: false,
					queryIds: [],
					GetDepartmentUserToSelectUrl: 'MES/MESOrderSC/GetDepartmentUserToSelect',
					SendEmailUrl: 'MES/MESOrderSC/SendEmail',
					label: '邮件发送',
					title: '机加请购',
					body: '机加请购',
					jsonM: ''
				},
				//项目搜索
				projectDetailSearch: '',
				//母工单搜索
				masterOrderSearch: '',
				//零件搜索
				partSearch: '',
				//子工单搜索
				childrenSearch: '',
				//步骤条id
				pdmProjectEL: 1,
				//第一个下一步
				oneIsDisableNext: false,
				//第二个下一步
				twoIsDisableNext: false,
				loadstatus: false,
				//零件维护工艺与交期弹出对话框
				partDialogVisable: false,
				openChildrenPanels: false,
				//整装散装下拉框
				readyorbulk: '',
				readyorbulks: ['整装', '散装'],
				//当前选中的所有项目
				currentSelectProjectItems: [],
				//正在选中的那一项s
				currentSelectOneProject: null,
				//子工单-日期组件弹出框
				childrenDeliverydateMenu: false,
				//子工单-交期
				childrenDeliverydate: format(parseISO(new Date().toISOString()), 'yyyy-MM-dd'),
				//母工单-日期组件弹出框
				deliverydateMenu: false,
				//母工单-交期
				deliverydate: format(parseISO(new Date().toISOString()), 'yyyy-MM-dd'),
				//交期维护对话框
				deliveryDateVisable: false,
				// 搜索：项目-项目号
				projectCode: '',
				//搜索：项目-项目名称
				projectName: '',
				// 搜索：项目的设备名称
				equipmentName: '',

				//选择的子工单类型
				selectChildrenOrderType: {},
				//子工单类型
				childrenOrderTypes: [],
				//选中的工单类型
				selectOrderType: {},
				//开立工单类型
				masterOrderTypes: [],
				projectLoadstatus: false,
				projectHeaders: [],
				projectData: [],

				projectLoading: true,
				projectTotalCount: 0,
				projectOptions: {
					//页数
					page: 1,
					//每页行数
					itemsPerPage: 5
				},
				vuetifyDefaultPage: {
					'items-per-page-text': '每页个数',
					'items-per-page-options': [5,10, 20, 50, 100]
					// 'items-per-page-all-text': '100'
				},
				vuetifyDefaultPageShowParts: {
					'items-per-page-text': '每页个数',
					'items-per-page-options': [50,200,300,500]
					// 'items-per-page-all-text': '100'
				},
				
				projectDetailHeaders: [],
				projectDetailData: [],

				//母工单头
				masterHeaders: [{
						text: '母工单号',
						value: 'workcode',
						filterable: true
					},
					{
						text: '项目号',
						value: 'projectcode',
						filterable: true
					},
					{
						text: '名称',
						value: 'name',
						filterable: true
					},
					{
						text: '工单类型',
						value: 'typename',
						filterable: true
					},
					{
						text: '交期',
						value: 'deliverydate',
						filterable: true
					},
					{
						text: '数量',
						value: 'qty',
						filterable: false
					},
					{
						text: '单位',
						value: 'unitname',
						filterable: false
					},
					{
						text: '版本号',
						value: 'versioncode',
						filterable: false
					},
					{
						text: '下发日期',
						value: 'issueddate',
						filterable: false
					},
					{
						text: '需求日',
						value: 'assemblydate',
						filterable: false
					},
					{
						text: '设计',
						value: 'design_username',
						filterable: false
					},
					{
						text: '核对',
						value: 'check_username',
						filterable: false
					},
					{
						text: '审核',
						value: 'audit_username',
						filterable: false
					},
					{
						text: '备注',
						value: 'description',
						filterable: false
					},
				],
				//母工单数据
				masterOrderData: [],
				childrenOrderData: [],
				// 当前选择项目的零件
				currentProjectPartList: [],
				selectPartinfo: {},
				//选中的母工单
				clickMasterOrder: {},
				//装配母工单下拉菜单信息
				assemblyMasterOrderItems: [],
				//选择装配母工单
				selectAssemblyMasterOrder: {}
			}
		},
		watch: {
			projectOptions: {
				handler() {
					this.loadProjectList()
				},
				deep: true
			}
		},
		methods: {
			// 分页跳转
			// goPage(pageNumber) {
			// 	this.pageModel.loading = true
			// 	this.pageModel.pagination.pageNumber = pageNumber
			// 	this.loadProjectList()
			// },
			refreshProjectQuery() {
				this.equipmentName = ''
				this.projectCode = ''
				this.projectName = ''
			},
			projectQuery() {

				this.loadProjectList()
			},
			// 加载项目信息（包含headers,data）
			loadProjectList() {
				var that = this
				this.projectLoading = true
				this.$httpRequest({
					url: `MES/MESOrderSC/GetProjectContainDetailList?
					equipmentName=${this.equipmentName}
					&projectCode=${this.projectCode}
					&projectName=${this.projectName}
					&projectDetailType=3
					&pageNumber=${this.projectOptions.page}
					&pageSize=${this.projectOptions.itemsPerPage}`,
					method: 'get',
				}).then(function(response) {
					if (response.status == 1) {
						that.projectHeaders = response.data.headers
						that.projectData = response.data.model.result
						that.projectTotalCount = response.data.model.pagination.totalRecords
						that.masterOrderTypes = response.data.other1
						that.childrenOrderTypes = response.data.other2
						if (that.currentSelectOneProject != null) {
							var temp = that.projectData.find(function(e) {
								return e.id == that.currentSelectOneProject.id
							})
							//测试A
							that.masterOrderData = temp.masterorderList
							that.currentSelectOneProject.projectDetailList = temp.projectDetailList
							// that.currentSelectOneProject.projectDetailList.forEach(r=>{
							//  console.log(	r.partList.length)
							// })
						}


						that.projectLoading = false
					} else {
						that.$message.error('加载项目数据失败')
					}
				})
			},
			//批量交期维护点击事件
			batchDeliveryDateEvent() {
				var selectItems = this.getProjectDetailCheckList()
				if (selectItems.length <= 0) {
					this.$message.warning("请选中任务明细")
				} else {
					this.deliveryDateVisable = true
				}
			},
			//交期维护
			deliveryDate() {
				//弹出对话框
				this.deliveryDateVisable = true
			},
			//获取项目明细选中项
			getProjectDetailCheckList() {
				var selectItems = []
				this.currentSelectProjectItems.forEach((item) => {
					item.projectDetailList.forEach((detail) => {
						if (detail.check)
							selectItems.push(detail.id)
					})
				})
				return selectItems
			},
			//选中当前项
			checkCurrentProjectDetail(item) {
				this.currentSelectProjectItems.forEach((item) => {
					item.projectDetailList.forEach((detail) => {
						detail.check = false
					})
				})
				item.check = true
			},
			//交期维护 保存
			save() {
				var selectItems = this.getProjectDetailCheckList()
				if (selectItems.count <= 0) {
					console.log('请选中需要维护的电控信息')
					return
				}
				// this.$httpRequest
				var that = this
				this.deliveryDateVisable = false
				this.$httpRequest({
					url: 'MES/MESOrderSC/GenerateMasterOrder',
					method: 'post',
					data: {
						"type": 3,
						"deliverydate": this.deliverydate,
						"projectdetailids": selectItems,
						"readyorbulk": this.readyorbulk
					}
				}).then(function(response) {
					if (response.status == 1) {
						that.$message.success(response.info)
						that.pdmProjectEL = 2
						that.loadProjectList()
						that.oneIsDisableNext = true
					} else {
						that.$message.error(response.info)
					}

				})
				this.deliverydate = ''
				this.readyorbulk = ''
			},
			close() {
				this.deliveryDateVisable = false
				this.deliverydate = ''
				this.readyorbulk = ''
			},
			//当前选中的所有项目
			currentSelectProjects(items) {
				this.currentSelectProjectItems = items
			},
			getColor(masterid) {
				if (masterid == null) return 'green'
				else return 'red'
			},
			// 每个项目选中事件
			itemProjectSelected(selectd) {
				this.masterOrderData = []
				var flag = false
				if (selectd.value) {
					this.currentSelectOneProject = selectd.item
					this.masterOrderData = selectd.item.masterorderList

					if (this.currentSelectOneProject.deliverydate != null)
						flag = true
				}
				this.oneIsDisableNext = flag
			},

			masterOrderCheckEvent(masterOrder) {
				if (masterOrder.value) {
					this.twoIsDisableNext = true
					this.clickMasterOrder = masterOrder.item
					this.currentProjectPartList = this.clickMasterOrder.partList
					this.childrenOrderData = this.clickMasterOrder.childrenWorkOrders
					// this.selectChildrenOrderTypeEvent()
				} else {
					this.twoIsDisableNext = false
				}
			},
			// 点击每条零件交期、工艺属性
			partItemClick(partinfo) {
				this.partDialogVisable = true
				this.selectPartinfo = partinfo
				this.selectChildrenOrderTypeEvent(partinfo);
			},

			// 保存零件维护交期和工艺属性
			async savePart() {
				this.partDialogVisable = false
				if (this.selectChildrenOrderType == null) {
					this.$message.error('工艺属性不能为空！')
					return
				}
				if (this.childrenDeliverydate == null) {
					this.$message.error('交期不能为空！')
					return
				}

				if (this.selectAssemblyMasterOrder == {}) {
					this.$message.error('请选择需要关联的装配母工单！')
					return
				}
				// 选择了类型为：委外请购
				if (this.selectChildrenOrderType == 5) {
					//弹出发送邮件组件
					this.emailCommentModel.sendEmailDialogVisable = true
					this.emailCommentModel.queryIds = [this.selectPartinfo.id]
					
					this.emailCommentModel.jsonM = JSON.stringify({
						deliverydate: this.childrenDeliverydate,
						projectcode: this.clickMasterOrder.projectcode,
						projectname: this.clickMasterOrder.projectname,
						equiname: this.clickMasterOrder.name
					})

				} else {
					this.createChildrenOrderSubmit()
					this.selectChildrenOrderType = ''
					this.childrenDeliverydate = ''
				}
			},
			//选择多个零件
      selectPartsEvent(parts){
				console.log(parts)
			},
			async createChildrenOrderSubmit() {
				var response = await this.$httpRequest({
					url: 'MES/MESOrderSC/GenerateChildrenOrder',
					method: 'post',
					data: {
						"type": this.selectChildrenOrderType,
						"deliverydate": this.childrenDeliverydate,
						"partId": this.selectPartinfo.id,
						"assemblymasterid": this.selectAssemblyMasterOrder.masterId
					}
				})

				if (response.status == 1) {
					this.$message.success(response.info)
					// 重新渲染子工单
					this.clickMasterOrder.childrenWorkOrders = this.childrenOrderData = response.data
						.childrenList
					// 重新渲染零件
					this.clickMasterOrder.partList = this.currentProjectPartList = response.data.partList

				} else {
					this.$message.error(response.info)
				}
			},
			closePart() {
				this.partDialogVisable = false
				// this.selectChildrenOrderType = ''
				// this.childrenDeliverydate = ''
			},

			//发送邮件回调函数
			sendEmailCallBack(flag) {
				if (flag) {
					this.createChildrenOrderSubmit()
					this.selectChildrenOrderType = ''
					this.childrenDeliverydate = ''
				}
			},
			async selectChildrenOrderTypeEvent(partinfo) {
				var response = await this.$httpRequest({
					url: `MES/MESOrderSC/LoadAssemblyMasterOrders?jgcode=${partinfo.code}&projectcode=${this.clickMasterOrder.projectcode}`,
					method: 'get'
				})
				if (response.status == 1) {
					this.selectAssemblyMasterOrder = response.data
				}

			},
			loadChildrenOrder() {
				this.currentProjectPartList = []
			},
			selectPartsEvent(){
				
			},
		}
	}
</script>
